import logging
import os
import tempfile
import traceback

from smb.SMBConnection import SMBConnection


def save_smb():
    try:
        conn = SMBConnection("administrator", 'sc158-vm02', "TEST", "sc158-vm02", domain="WorkGroup")
        conn.connect("192.168.31.151")
        # conn.listShares()
        sharelist = conn.listPath("zlpdf", "big_json")  # 列出共享目录
        for i in sharelist:

            if i.filename == "." or i.filename == "..":
                continue
            print(i.filename)
            for j in conn.listPath("zlpdf", "big_json/" + i.filename):
                if j.filename == "." or j.filename == "..":
                    continue
                file_path = 'big_json/{}/{}'.format(i.filename, j.filename)
                print(file_path)
                file_obj = tempfile.NamedTemporaryFile()
                file_attributes, filesize = conn.retrieveFile('zlpdf', file_path, file_obj)
                file_obj.seek(0)
                file_str = file_obj.read().decode('utf-8')

                file_obj.close()
            # print(filesize)
            # print(file_attributes)
            # print(i.filename)
            # print(file_obj)
            # file_obj.seek(0)
            # # print(file_obj.read().decode('utf-8'))
            # file_obj.close()
        # print(sharelist)
        # conn.createDirectory(self.server_name, self.nowdate)
    except:
        print(traceback.format_exc())
    # try:
    #     filepath = self.nowdate + "/{}.txt".format(self.beforedate)
    #     conn.deleteFiles(self.server_name, filepath)
    #     f = open(self.tempfile, "rb")
    #     conn.storeFile(self.server_name, filepath, f)
    #     f.close()
    #     if os.path.exists(self.tempfile):
    #         os.remove(self.tempfile)
    #     print("今日更新上传到smb成功")
    # except:
    #     logging.warning("上传smb出错")


save_smb()
